"use client";
import React, { memo, useState, useEffect } from "react";
import type { FC, ReactNode } from "react";
import Image from "next/image";
import myLogo from "@/assets/img/MyAI Logo.png";
import "./css/index.css";
import { userService, chatService } from "@/services/api";
import { RootState } from "@/store/store";
import { eventBus } from "@/utils/eventBus";
import { useSelector, useDispatch } from "react-redux";
import dayjs from "dayjs";
import { setChatId } from "@/store/reducers/chatIdReducer";
import { useRouter } from "next/navigation"; // 引入 useRouter
import DeleteIcon from "@/assets/icons/删除.svg";
import { useAuthhook } from "@/hooks/useAuth";

interface IProps {
  children?: ReactNode;
}
interface ChatItem {
  id: string;
  user_id: number;
  chatDate: string;
  chatTitle: string;
}
// const Infolist = [
//   {
//     id: 11,
//     userId: 1,
//     chatData: "2023.10.1",
//     chatTitle: "测试标题",
//   },
//   {
//     id: 12,
//     userId: 1,
//     chatData: "2023.10.1",
//     chatTitle: "测试标题2",
//   },
// ];

const MySlideNav: FC<IProps> = () => {
  const [Infolist, setInfolist] = useState<ChatItem[]>([]);
  // const { userId, email } = useSelector((state: RootState) => state.auth);
  const dispatch = useDispatch();
  const chatIdNow = useSelector((state: RootState) => state.chatId.chatId);
  const router = useRouter(); // 初始化 useRouter
  const { ituser } = useAuthhook();
  const email = ituser?.email;

  useEffect(() => {
    if (!email) return;
    onGetList();
    const handleRefreshChats = () => {
      onGetList();
    };

    eventBus.on("refreshChats", handleRefreshChats);

    return () => {
      eventBus.off("refreshChats", handleRefreshChats);
    };
  }, [ituser]);

  const onGetList = () => {
    if (!email) return;
    userService.getUser(email).then((res) => {
      console.log(res);

      const chats = res.user.chats || [];

      // 按日期降序排序
      const sortedChats = [...chats].sort(
        (a, b) =>
          new Date(b.chatDate).getTime() - new Date(a.chatDate).getTime()
      );

      setInfolist(sortedChats);
    });
  };
  return (
    <div className="slide-nav">
      <div className="head-n-logo">
        <div className="head-title">My AI</div>
        <Image src={myLogo} alt="logo" className="head-logo" />
      </div>
      <div className="new-talking">
        <div
          className="new-talking-btn"
          onClick={() => {
            dispatch(setChatId(""));
            router.push("/talking");
          }}
        >
          + 新对话
        </div>
      </div>
      <div className="nav-list">
        {Infolist.length === 0 ? (
          <div
            style={{
              textAlign: "center",
              width: "100%",
              height: "20px",
              lineHeight: "20px",
              fontSize: "20px",
              marginTop: "20px",
            }}
          >
            您还没有对话，快去创建吧！
          </div>
        ) : (
          Infolist.map((item) => (
            <div
              key={item.id}
              className={`nav-item ${item.id === chatIdNow ? "my-active" : ""}`}
            >
              <div
                className="nav-item-title"
                onClick={() => {
                  dispatch(setChatId(item.id));
                  router.push(`/chat/${item.id}`);
                }}
              >
                <div>{item.chatTitle}</div>
                <div>{dayjs(item.chatDate).format("YYYY-MM-DD")}</div>
              </div>
              <Image
                src={DeleteIcon}
                alt="删除图标"
                className="delete-icon"
                onClick={async () => {
                  const isConfirmed = window.confirm("确定要删除该对话吗？");
                  if (!isConfirmed) return;

                  try {
                    const res = await chatService.deleteChat(item.id);
                    console.log("删除成功", res);
                    onGetList(); // 刷新列表
                    // eventBus.emit("refreshChats"); // 触发其他组件刷新
                  } catch (error) {
                    alert("删除失败，请稍后再试。");
                    console.error("删除出错", error);
                  }
                }}
              />
            </div>
          ))
        )}
      </div>
    </div>
  );
};
export default memo(MySlideNav);
